#include<stdio.h>
#include<getopt.h>
#include<stdlib.h>

const char *program_name;

void print_usage(FILE *stream,int exit_code)
{
  fprintf(stream,"Usage: %s options [ inputfile...]\n",program_name);
  fprintf(stream," -h  --help  print the help information.\n"
          " -o  --output filename .\n"
          " -V  --version print version information.\n");
  exit(exit_code);
}
          

int main(int argc, char *argv[])
{
  int next_option;
  int haveargv = 0;
  int haveoutput = 0;
  int haveinput = 0;

  const char * const short_options = "ho:i:v";

  const struct option long_options[] = {
    {"help",0,NULL,'h'},
    {"output",1,NULL,'o'},
    {"input",1,NULL,'i'},
    {"version",0,NULL,'v'},
    {0,0,0,0}
  };

  const char * output_filename = NULL;
  const char * input_filename = NULL;

  int verbose = 0;

  program_name = argv[0];

  do
    {
      next_option = getopt_long(argc,argv,short_options,long_options,NULL);
      switch(next_option)
        {
        case 0:
          printf("the switch get zero!!");
          break;
        case 'h':
          haveargv = 1;
          print_usage(stdout,0);
          break;
        case 'o':
          output_filename = optarg;
          haveoutput = 1;
          haveargv = 1;
          break;
        case 'i':
          haveargv = 1;
          haveinput = 1;
          input_filename = optarg;
          break;
        case 'v':
          verbose = 1;
          haveargv = 1;
          printf("get option \'version\'");
          break;
        case ':':
          printf("the switch get :!!");
          break;
        case '?':
          print_usage(stderr,1);
        case  -1:
          if(!haveargv)
            {
              print_usage(stderr,1);
            }
          break;
        default:
          print_usage(stderr,1);
          break;
        }
    }while(next_option !=  -1);

  if(verbose)
    {
      int i;
      for(i = optind;i<argc;++i)
        printf("Argument:%s\n",argv[i]);
    }

  if(haveoutput)
    printf("output: %s\n",output_filename);

  if(haveinput)
    printf("input: %s\n",input_filename);

  return 0;
}
